#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

int g_bowl = 1;

pthread_mutex_t g_lock;

pthread_cond_t g_cond;

void* EatStart(void* arg)
{
    while(1)
    {
        pthread_mutex_lock(&g_lock);
        while(g_bowl <= 0)
        {
            //等待
            pthread_cond_wait(&g_cond, &g_lock);
        }
        g_bowl--;
        printf("i am %p, i eat %d\n",pthread_self(),g_bowl);//g_bowl大于0就执行
        pthread_mutex_unlock(&g_lock);
        pthread_cond_signal(&g_cond);//通知做面
    }
    return NULL;
}

void* MakeStart(void* arg)
{
    while(1)
    {
        pthread_mutex_lock(&g_lock);
        while(g_bowl > 0)
        {
            //大于0，说明有面就等待
            pthread_cond_wait(&g_cond, &g_lock);
        }
        g_bowl++;
        printf("i am %p, i make %d\n",pthread_self(),g_bowl);
        pthread_mutex_unlock(&g_lock);
        pthread_cond_signal(&g_cond);
    }
    return NULL;
}

int main()
{
    pthread_mutex_init(&g_lock,NULL);

    pthread_cond_init(&g_cond,NULL);
    for(int i = 0; i < 2; i++)
    {
        pthread_t tid;
        int ret = pthread_create(&tid,NULL,EatStart,NULL);
        if(ret < 0)
        {
            perror("pthread_create");
            return 0;
        }
        ret = pthread_create(&tid,NULL,MakeStart,NULL);
        if(ret < 0)
        {
            perror("pthread_create");
            return 0;
        }
    }
    while(1)
    {
        sleep(1);
    }

    pthread_cond_destroy(&g_cond);
    pthread_mutex_destroy(&g_lock);

    return 0;
}
